<template>
  <div>
    <a-card>
      <h3 style="text-align: center">{{ id ? '编辑文章' : '添加文章' }}</h3>
      <a-form-model
        :model="artInfo"
        ref="artInfoRef"
        :rules="artInfoRules"
        :hideRequiredMark="true"
      >
        <a-form-model-item label="文章标题" prop="title">
          <a-input style="width: 300px" v-model="artInfo.title"></a-input>
        </a-form-model-item>

        <a-form-model-item label="文章分类" prop="cid">
          <a-select
            v-model="artInfo.cid"
            @change="cateChange"
            listType="picture"
          >
            <a-select-option :value="0">未分类</a-select-option>

            <a-select-option
              v-for="(item, index) in cateList"
              :key="index + item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="文章描述" prop="desc">
          <a-input v-model="artInfo.desc"></a-input>
        </a-form-model-item>

        <a-form-model-item label="文章缩略图" prop="img">
          <a-upload
            name="file"
            listType="picture"
            :multiple="false"
            :customRequest="uploadImg"
            accept="image/jpeg,image/jpg,image/png"
          >
            <a-button> <a-icon type="upload" /> 点击上传 </a-button>
          </a-upload>
          <br />
          <template v-if="artInfo.img">
            <img :src="artInfo.img" style="width: 120px; height: 100px" />
          </template>
        </a-form-model-item>

        <a-form-model-item label="文章内容" prop="content">
          <!-- <a-input type="textarea" v-model="artInfo.content"></a-input> -->
          <mavon-editor v-model="artInfo.content" codeStyle="monokai" />
        </a-form-model-item>

        <a-form-model-item>
          <a-button
            type="primary"
            style="margin-right: 15px"
            @click="artOK(artInfo.id)"
            >{{ artInfo.id ? '更新' : '提交' }}</a-button
          >
          <a-button type="danger" @click="addCancel">取消</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-card>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'

export default {
  props: ['id'],
  data () {
    return {
      artInfo: {
        id: 0,
        title: '',
        cid: 0,
        desc: '',
        content: '',
        img: '',
      },
      cateList: [],
      upUrl: '',
      artInfoRules: {
        title: [
          { required: true, message: '请输入文章标题！', trigger: 'blur' },
        ],
        cid: [{ required: true, message: '请输入文章标题！', trigger: 'blur' }],
        desc: [
          { required: true, message: '请输入文章标题！', trigger: 'blur' },
          { max: 120, message: '描述最多可写120个字符！', trigger: 'change' },
        ],
        // img: [{ required: true, message: '请选择缩略图！', trigger: 'blur' }],
        content: [
          { required: true, message: '请输入文章内容！', trigger: 'blur' },
        ],
      },
      credentials: {},
    }
  },
  created () {
    this.getCateList()
    this.headers = {
      Authorization: `Bearer ${window.sessionStorage.getItem('token')}`,
    }
    if (this.id) {
      this.getArtInfo(this.id)
    }
  },
  methods: {
    // 查询文章信息
    async getArtInfo (id) {
      const { data: res } = await this.$http.get(`article/info/${id}`)
      if (res.status !== 200) return this.$message.error(res.message)
      this.artInfo = res.data
      this.artInfo.id = res.data.ID
    },
    // 获取文章分类
    async getCateList () {
      const { data: res } = await this.$http.get('categorys')
      if (res.status !== 200) return this.$message.error(res.message)
      this.cateList = res.data
    },
    // 选择分类
    cateChange (value) {
      this.artInfo.cid = value
    },
    uploadChange (info) {
      console.log('uploadChange')
      if (info.file.status !== 'uploading') {
      }
      if (info.file.status === 'done') {
        this.$message.success('图片上传成功！')
      } else if (info.file.status === 'error') {
        this.$message.error('图片上传失败！')
      }
    },

    uploadImg (info) {
      // todo (new Date()).getTime()
      const imgKey = '/articleImg/' + info.file.name
      var cos = new COS({
        // 必选参数
        getAuthorization: (options, callback) => {
          this.$http
            .get('cos/credential', { params: { userImgPath: imgKey } })
            .then(res => {
              res = res.data
              if (res.status !== 200) return this.$message.error(res.message)
              var credentials = res.data.Credentials
              if (!credentials) return this.$message.error('无上传权限！')
              const credential = {
                TmpSecretId: credentials.TmpSecretId,
                TmpSecretKey: credentials.TmpSecretKey,
                XCosSecurityToken: credentials.Token,
                // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                StartTime: res.data.StartTime, // 时间戳，单位秒，如：1580000000
                ExpiredTime: res.data.ExpiredTime, // 时间戳，单位秒，如：1580000900
              }
              callback(credential)
            })
        },
      })
      // 上传到cos
      cos.putObject(
        {
          Bucket: 'ginblog-1302428193' /* 必须 */,
          Region: 'ap-chengdu' /* 存储桶所在地域，必须字段 */,
          Key: imgKey /* 必须 */,
          StorageClass: 'STANDARD',
          Body: info.file, // 上传文件对象
          onProgress: progressData => {
            // console.log(JSON.stringify(progressData))
          },
        },
        (err, data) => {
          if (err) return this.$message.error('上传失败！')
          this.artInfo.img = 'http://' + data.Location
          this.$message.success('图片上传成功！')
        }
      )
    },
    // 提交&&更新 文章
    artOK (id) {
      this.$refs.artInfoRef.validate(async valid => {
        if (id === 0) {
          const { data: res } = await this.$http.post(
            'article/add',
            this.artInfo
          )
          if (res.status !== 200) return this.$message.error(res.message)
          this.$message.success('添加成功！')
          this.$router.push('/admin/artlist')
        } else {
          const { data: res } = await this.$http.put(
            `article/${id}`,
            this.artInfo
          )
          if (res.status !== 200) return this.$message.error(res.message)
          this.$message.success('编辑成功！')
          this.$router.push('/admin/artlist')
        }
      })
    },

    addCancel () {
      this.$refs.artInfoRef.resetFields()
      this.$message.info('已取消！')
      this.$router.push('/admin/artlist')
    },
  },
}
</script>

<style></style>
